// pages/detail/detail.js
var util = require('../../utils/util.js')
const DB = wx.cloud.database()
const $ = DB.command.aggregate
const _ = DB.command
//获取应用实例
const app = getApp()

let bookname = ""
let skip = 10
let skipx = -1
let bookid = ""

Page({

  /**
   * 页面的初始数据
   */
  data: {
    //处理导 航 栏的高度
    rpxdata: wx.getStorageSync('rpxdata'),
    navigationBarAndStatusBarHeight: wx.getStorageSync('statusBarHeight') + wx.getStorageSync('navigationBarHeight') + 'px',
    navigationBarAndStatusBarAndsearchHeight: wx.getStorageSync('statusBarHeight') + wx.getStorageSync('navigationBarHeight') + 60 + 'px',
    //设置导航栏的显示信息
    navbarData: {
      showCapsule: 0,
      title: "懒小丫图书管理"
    },
    //用户身份信息
    openid: wx.getStorageSync('openid'),
    nickname: "",
    userInfo: {},
    register: 0,
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),

    DBget: {},
    DBlength: 1,
    //是否显示到底
    bottom_info : 0,
    giftNo: 0,
    jyren: "刘春红",

    //查询数据
    op1: "",
    op2: "",
    op3: "",
    //搜索框输入信息
search_text: ""

  },

  //借书
  jieshu(e) {
    let that = this
    let id = e.currentTarget.dataset.id
    let stock = e.currentTarget.dataset.stock
    if (that.data.nickname == "") {
      wx.showToast({
        title: '请开通权限',
        image: '/images/fail.png',
        duration: 2000
      })
    } else {
      if (that.data.register == 0) {
        wx.showToast({
          title: '未审核通过',
          image: '/images/fail.png',
          duration: 2000
        })
      } else {
        if (stock == 0) {
          wx.showToast({
            title: '书被人借走了',
            duration: 3000,
            image: '/images/fail.png',
          })
        } else {
          wx.showModal({
            title: '懒小丫提醒',
            content: '你确认要借这本书吗？',
            success(res) {
              if (res.confirm) {
                DB.collection("lchbook").doc(id).update({
                  data: {
                    jyren: that.data.nickname,
                    openid: that.data.openid,
                    jystate: true,
                    jytime: util.formatTime(new Date()),
                    jydate: util.formatDate(new Date()),
                    stock: stock - 1
                  }
                })
                DB.collection("lchbook").skip(0).limit(10).get().then(res => {
                  that.setData({
                    DBget: res.data,
                    bottom_info:0
                  })
                   skip = 10
                })
              }
            }
          })
        }
      }
    }
  },

  //搜索框输入信息
  search(e){
    this.setData({search_text:e.detail.value})
  },
  
  //扫码信息
  isbn(){
    let that = this
    wx.scanCode({
      onlyFromCamera: true,
      success:function(res){that.setData({search_text:res.result})},
      fail:function(){wx.showToast({
        title: '扫码失败请手工输入',duration:2000
      })}
    })
  },

searchClickEvent(){
  let that = this
  DB.collection("lchbook").where(_.or([{bookname:DB.RegExp({regexp:that.data.search_text,options:"i"})},{isbn:DB.RegExp({regexp:that.data.search_text,options:"i"})}])).skip(0).limit(10).get({success:function(res){
    that.setData({DBget:res.data,
     DBlength: res.data.length})}})
},

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this
    //获取导航栏高度
    this.setData({
      navigationBarAndStatusBarAndsearchHeight: wx.getStorageSync('statusBarHeight') + wx.getStorageSync('navigationBarHeight') + this.data.rpxdata * 122 + 'px'
    })

    this.setData({
      op1: options.op1,
      op2: options.op2,
      op3: options.op3
    })


  DB.collection("lchbook").skip(0).limit(10).get({success:(res)=>{
    this.setData({
      DBget: res.data,
      DBlength: res.data.length
    })
  }
  })



  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.setData({openid: wx.getStorageSync('openid')})

    //获取用户注册状态
    DB.collection("lchuser").where({
      openid: this.data.openid
    }).get({
      success: (res) => {
        this.setData({
          register: res.data[0].register
        })
      }
    })

    /*
    console.log("op1",this.data.op1)
    console.log("op2",this.data.op2)
    console.log("op3",this.data.op3)
    if (this.data.op1 == 'order') {console.log("1111")}
    else {console.log("2222")}
*/
    /*
   if (that.data.op1 == "order")  {console.log("1111")
     if (that.data.op2 == 'uptime'){DB.collection("lchbook").orderBy('uptime','desc').skip(0).limit(10).get({success:function(res){that.setData({DBget:res.data})}})}
     else {DB.collection("lchbook").orderBy('jynum','desc').skip(0).limit(10).get({success:function(res){console.log("33333")}})}
   } else {
     if (that.data.op2  == 'bookclass'){DB.collection("lchbook").where({bookclass:that.data.op3}).skip(0).limit(10).get({success:function(res){that.setData({DBget:res.data})}})}
     else {console.log("shaoma".that.data.op3)}
   }
  */



  //tabbar显示
  if (typeof this.getTabBar === 'function' && this.getTabBar()) {
    this.getTabBar().setData({
      curIndex: wx.getStorageSync('curIndex')
    })
  }

  //获取头像相关信息，是否显示按钮 
  if (app.globalData.userInfo) {
    this.setData({
      userInfo: app.globalData.userInfo,
      hasUserInfo: true,
      nickname: app.globalData.userInfo.nickName
    })
  } else if (this.data.canIUse) {
    // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
    // 所以此处加入 callback 以防止这种情况
    app.userInfoReadyCallback = res => {
      this.setData({
        userInfo: res.userInfo,
        hasUserInfo: true,
        nickname: app.globalData.userInfo.nickName
      })
    }
  } else {
    // 在没有 open-type=getUserInfo 版本的兼容处理
    wx.getUserInfo({
      success: res => {
        app.globalData.userInfo = res.userInfo
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true,
          nickname: res.userInfo.nickName
        })
      }
    })
  }

},

/**
 * 生命周期函数--监听页面隐藏
 */
onHide: function () {

},

/**
 * 生命周期函数--监听页面卸载
 */
onUnload: function () {

},

/**
 * 页面相关事件处理函数--监听用户下拉动作
 */
onPullDownRefresh: function () {

},

/**
 * 页面上拉触底事件的处理函数
 */
onReachBottom: function () {

  let that = this
  let vvv = this.data.DBget
  DB.collection("lchbook").skip(skip).limit(10).get({success:(res)=>{
    vvv = that.data.DBget.concat(res.data)
    if (res.data.length == 0) {that.setData({bottom_info: 1 })}
    else { that.setData({DBget:vvv})   
    skip = skip + 10
  }
  }
  })

},

/**
 * 用户点击右上角分享
 */
onShareAppMessage: function () {

}
})